// const xPathMap = new Map();
const platformMap = new Map();  //平台信息
const baseEleMaps = new Map();  //基础信息 <==> DOM映射
const keyWords = new Map();
const matchWords = new Map();

/**
 * 1. 接收background的通知 background ==> content
 * 2. 获取商品信息
 * 3. 将商品信息返回    content ==> background
 */
window.onload = function() {
    console.log('content load!');
    if(window.location.href.indexOf(properties.scmURL) > -1) {
        var userJson = sessionStorage.getItem('GD_FAAS_LOGIN_USER')
        const userInfo = JSON.parse(userJson || '{}');
        chrome.runtime.sendMessage({ action: "saveUserInfo", uname: userInfo.userName, uid: userInfo.userId }, function(response) {
            console.log("saveUserInfo" + response);
        })
    }
}

function getInfo(request) {
    const platform = request.platform;
    const message = getItemsInfo(platform);
    doFormatData(message);
    return message;
}

function openZyConfirm() {
    // 使用 Bootstrap 的 JavaScript 方法显示 Modal
    var userConfirmation = window.confirm('将打开商品页面进行采集，是否打开？');
    if (userConfirmation) {
        // 用户点击了确定
        document.getElementsByClassName("item-title-text")[0].click()
    } else {
        // 用户点击了取消
        return;
    }
}

function openConfirm() {
     // 使用 Bootstrap 的 JavaScript 方法显示 Modal
     var userConfirmation = window.confirm('未识别到找样人，是否登录中台系统？');
     if (userConfirmation) {
         // 用户点击了确定
         window.open('http://scm.zhr08.com/gdpaas/login/index.htm', '_blank');
        //  window.open('http://qzzhr.puc123.cn/gdpaas/login/index.htm', '_blank');
     } else {
         // 用户点击了取消
         return;
     }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log(request, sender);
    if (request.action && request.action === "getInfo") {
        //返回响应信息
        const message = getInfo(request);
        sendResponse({ response: message }); // 在回调中发送响应
    } else if (request.action === "open_confirm") {
        // 使用 Bootstrap 的 JavaScript 方法显示 Modal
       openConfirm();
    } else if (request.action === 'button'){
        // 创建一个按钮元素
        var button = document.createElement("div");
        button.classList.add("dyBox");
        button.innerHTML = "<div class=\"hover-text\" ></div>"
        // 添加按钮点击事件处理程序
        button.addEventListener("click", function() {
            // 在页面脚本中发送消息给后台脚本请求存储数据
            chrome.runtime.sendMessage({ action: "getStorageData" }, function(response) {
                if(response && response.uname) {
                    const url  = window.location.href;
                    /**
                     * 识别平台
                     */
                    var platform = (url.indexOf("detail.tmall.com") > -1 || url.indexOf("item.taobao.com") > -1) ? "淘宝" : 
                        (url.indexOf("detail.vip.com") > -1 ? "唯品会" : 
                            (url.indexOf("item.jd.com") > -1 ? "京东" : 
                                (url.indexOf("detail.1688.com") > -1 ? "1688" : (
                                    url.indexOf("haohuo.jinritemai.com") > -1 ? "抖音" : (
                                        url.indexOf("sooxie.com/detail") > -1 ? "搜鞋" : (
                                            url.indexOf("xiaohongshu.com") > -1 ? "小红书" : ''
                                        )
                                    )))
                            )
                        );
                    if(platform != '' && platform != null) {
                        const message = getInfo({"platform": platform,"action": "getInfo"});
                        if(message) {
                            const params = message; 
                            params.url = url;
                            params.platform = platform;
                            params.uname = response.uname;
                            params.uid = response.uid;
                            const encodedParams = encodeURIComponent(JSON.stringify(params));
                            chrome.runtime.sendMessage({ action: "openNewTab", url: "newpage.html?data=" + encodedParams });
                        }
                    } else {
                        var otherPlatform = url.indexOf("data.zhiyitech.cn") > -1 ? "知衣" : "";
                        if(otherPlatform == '知衣') {
                            // var msg = "即将打开商品页面进行采集，是否打开";
                            // chrome.tabs.sendMessage(tabId, {"platform": otherPlatform,"action": "open_zy_confirm","msg": msg}, function(response) {
                            //   console.log(response);
                            // })
                            openZyConfirm();
                          }
                    }
                } else {
                    openConfirm();
                }
            });
        });
        // 将按钮添加到页面中的元素
        document.body.appendChild(button);
        sendResponse({ response: "succ" }); // 在回调中发送响应
    } else if(request.action === 'open_zy_confirm') {
        openZyConfirm();
    } else if(request.actoin === 'fromZy') {
        console.log(request)
    }
});

function doFormatData(obj) {
    var title = obj.title;
    var gender = obj.gender; 
    if((gender == null || gender == '') && title) {
        const regex = /男|女/g;
        const matches = title.match(regex);
        var set = new Set(matches);
        if(set.size > 0) {
            obj.gender = new Array(...set)[0];
        }
    }
    obj.saleDesc = convertChineseNumber(obj.saleDesc || '')
}

/**
 * @param {tb淘宝、vip唯品会} platform 
 */
function initMaps(platform) {
    if(platform) { //根据平台信息设置映射
        var p = platformMap.get("platform");
        if(platform != p) {
            if(platform == "淘宝") {
                initTbMaps();
            } else if(platform == "唯品会") {
                initVipMaps();
            } else if(platform == "京东") {
                initJdMaps();
            } else if(platform == '1688') {
                init1688Maps();
            } else if(platform == '抖音') {
                initDyMaps();
            } else if(platform == '搜鞋') {
                initSxMaps();
            } else if(platform == '小红书') {
                initXhsMaps();
            }
            //设置映射值
        } else {
            //未切换平台，无需重复设置映射
        }
    }
}

function convertChineseNumber(str) {
    // 新的正则表达式匹配数字和中文单位，包括小数部分
    if (str) {
        var match = str.match(/(\d+(\.\d+)?)(百|千|万)?/);
        if (match) {
            var number = parseFloat(match[1]); // 提取数字部分并转换成浮点数
            var unit = match[3]; // 提取中文单位部分
            // 根据不同的中文单位进行转换
            if (unit === "百") {
                return number * 100;
            } else if (unit === "千") {
                return number * 1000;
            } else if (unit === "万") {
                return number * 10000;
            } else {
                return number; // 如果没有中文单位，则直接返回数字
            }
        } else {
            return NaN; // 如果匹配失败，则返回 NaN
        }
    } else {
        return str;
    }
}

function initSxMaps() {
    platformMap.set("platform", "搜鞋");

    baseEleMaps.set("price", "meri-price");   //售价
    baseEleMaps.set("title", "shop-title");   //商品名称
    baseEleMaps.set("shop", "slb-title");  //店铺名称

    keyWords.clear();
    keyWords.set("color", ["颜色"]);
    keyWords.set("size", ["尺码","鞋码"]);
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节","上市时间"]);
    keyWords.set("style",["款式"]);
    keyWords.set("gender", ["性别"])

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

//小红书
function initXhsMaps() {
    platformMap.set("platform", "小红书");

    baseEleMaps.set("title", "goods-name");   //商品名称
    baseEleMaps.set("shop", "seller-name");  //店铺名称

    keyWords.clear();
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节","上市时间"]);
    keyWords.set("style",["款式"]);
    keyWords.set("gender", ["性别"]);

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

function initDyMaps() {
    platformMap.set("platform", "抖音");

    baseEleMaps.set("price", "price-line__price-container__price__amount");   //售价
    baseEleMaps.set("extraPrice", "price-line__price-container__discount-price__amount");   //折扣价
    baseEleMaps.set("title", "title-info__text");   //商品名称
    baseEleMaps.set("shop", "shop-component__shop-content__basic-info__title-area__name");  //店铺名称

    keyWords.clear();
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节","上市时间"]);
    keyWords.set("style",["款式"]);
    keyWords.set("gender", ["性别"])

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

function initJdMaps() {
    platformMap.set("platform", "京东");
    baseEleMaps.clear();
    // baseEleMaps.set("title", "@pageConfig.product.name"); //商品名称
    // baseEleMaps.set("price", "price J-p-100045763160");   //售价
    // baseEleMaps.set("shop", "shop-name");    //店铺名称
    baseEleMaps.set("title", "sku-name");   //商品名称
    
    keyWords.clear();
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节","上市时间"]);
    keyWords.set("style",["款式"]);
    keyWords.set("gender", ["性别"])

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

function initVipMaps() {
    platformMap.set("platform", "唯品会");

    baseEleMaps.clear();
    baseEleMaps.set("title", "pib-title-detail"); //商品名称
    baseEleMaps.set("price", "sp-price");   //售价
    baseEleMaps.set("shop", "re-store-name");  //店铺名称 唯品会显示品牌名称
    baseEleMaps.set("color", "+color-item-name");
    baseEleMaps.set("size", "+size-list-item-name");

    keyWords.clear();
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节"]);
    keyWords.set("style", ["款式"]);
    keyWords.set("gender", ["性别"])

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

function init1688Maps() {
    platformMap.set("platform", "1688");
    baseEleMaps.clear();

    baseEleMaps.set("title", "title-text"); //商品名称
    baseEleMaps.set("price", "price-text");   //售价
    baseEleMaps.set("saleDesc", "ItemHeader--salesDesc--srlk2Hv");  //销量

    // baseEleMaps.set("shop", "re-store-name");  //店铺名称 唯品会显示品牌名称
    // baseEleMaps.set("color", "+color-item-name");

    keyWords.clear();
    keyWords.set("color", ["颜色"])
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节"]);
    keyWords.set("style", ["产品类别"]);
    keyWords.set("size", ["尺码","鞋码"]);
    keyWords.set("gender", ["性别"]);

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}

function initTbMaps() {
    platformMap.set("platform", "淘宝");

    baseEleMaps.clear();
    baseEleMaps.set("title", ["ItemHeader--mainTitle--3CIjqW5", "ItemHeader--mainTitle--1rJcXZz f-els-2",'ItemTitle--mainTitle--2OrrwrD f-els-2','mainTitle--O1XCl8e2 f-els-2']); //商品名称
    baseEleMaps.set("saleDesc", ["ItemHeader--salesDesc--srlk2Hv","ItemHeader--salesDesc--1l_cuh6",'itemWrap--asonyoQ3']);  //销量
    baseEleMaps.set("price", ["Price--priceText--2nLbVda","Price--priceText--1oEHppn",'priceText--gdYzG_l_']);   //售价
    baseEleMaps.set("extraPrice", ["Price--priceText--2nLbVda Price--extraPriceText--2dbLkGw", "Price--priceText--1oEHppn Price--extraPriceText--3zUb0uS",'priceText--gdYzG_l_ extraPriceText--aysuZjG_']);
    baseEleMaps.set("shop", ["ShopHeaderNew--shopName--2J0piSC","ShopHeader--shopName--zZ3913d",'shopName--mTDZGIPO']);  //店铺名称
    
    keyWords.clear();
    keyWords.set("color", ["颜色分类"])
    keyWords.set("size", ["尺码","鞋码"])
    keyWords.set("year", ["上市时间","上市年份"]);   //年份
    keyWords.set("season",["季节","上市时间"]);    //季节
    keyWords.set("style", ["款式"]);    //品类
    keyWords.set("gender", ["性别"])

    matchWords.clear();
    matchWords.set("season", /春|夏|秋|冬/g);   //季节
    matchWords.set("year", /(\d{4})/g);
    matchWords.set("gender", /男|女/g)
}
/**
 * 根据页面DOM元素获取商品要素信息
 */
function getItemsInfo(platform) {
    initMaps(platform);
    //根据DOM映射获取信息
    let retItems = {};
    for (let [key, value] of baseEleMaps) {
        if(value instanceof Array) {
            value.forEach(item => setBaseEleMapsValue(key, item, retItems))
        } else {
            setBaseEleMapsValue(key, value, retItems);
        }
    }
    getBaseInfoByPlatform(platform, retItems);
    getPicByPlatform(platform, retItems);   //获取图片信息
    return retItems;
}

function setBaseEleMapsValue(key, value, retItems) {
    var b = value.startsWith("+");
    if(b) { //@ 表示取所有元素 +
        value = value.substring(1);
    }
    var doms = document.getElementsByClassName(value);
    if(doms && doms.length > 0) {
        if(b) {
            retItems[key] = "";
            Array.from(doms).forEach(dom => retItems[key] += (dom.innerText + " "))
        } else {
            if(!retItems[key]) {
                retItems[key] = doms[0].innerText;
            }
        }
    }
}

function getBaseInfoByPlatform(platform, obj) {  //根据平台获取基本信息,填充返回值
    if(platform == "淘宝") {
        getBaseInfoFromTb(obj);
    } else if(platform == "唯品会") {
        getBaseInfoFromVip(obj);
    } else if(platform == "京东") {
        getBaseInfoFromJD(obj);
    } else if(platform == '1688') {
        getBaseInfoFrom1688(obj);
    } else if(platform == '抖音') {
        getBaseInfoFromDy(obj);
    } else if(platform == '搜鞋') {
        getBaseInfoFromSx(obj);
    } else if(platform == '小红书') {
        getBaseInfoFromXhs(obj);
    }
}

function getPicByPlatform(platform, obj) {
    if(platform == "淘宝") {
        var picGallerys = document.getElementsByClassName("PicGallery--thumbnailPic--1spSzep");
        if(!picGallerys || picGallerys.length == 0) {
            picGallerys = document.getElementsByClassName("PicGallery--thumbnailPic--nbPtwNj");
        }
        if(!picGallerys || picGallerys.length == 0) {
            picGallerys = document.getElementsByClassName("thumbnail--TxeB1sWz");
        }
        if(picGallerys && picGallerys.length > 0) {
            obj["imageUrls"] = [];
            Array.from(picGallerys).forEach(item => {
                var imgURL = item.src;
                if(!imgURL) {
                    imgURL = item.getElementsByTagName('IMG')[0].src;
                }
                if(imgURL.indexOf("110x10000") > -1) {
                    imgURL = imgURL.replaceAll("110x10000", "");
                } else if(imgURL.indexOf("240x10000") > -1) {
                    imgURL = imgURL.replaceAll("240x10000", "");
                }
                obj["picture"] = imgURL;
                obj["imageUrls"].push(imgURL)
            }); 
        }
    } else if(platform == "唯品会") {
        var picGallerys = document.getElementById('J-img-content').getElementsByClassName('pic-slider-items');
        if(picGallerys) {
            obj["imageUrls"] = [];
            Array.from(picGallerys).forEach(item => {
                var picGalChildren = item.children;
                if(picGalChildren && item.childElementCount > 0) {
                    var playMarked = false;
                    if(item.childElementCount == 2) {
                        playMarked = picGalChildren[0].className == 'vjs-icon-play small-image-play-icon'
                    }
                    if(!playMarked) {
                        var picDom = Array.from(picGalChildren).find(element => element.nodeName == 'IMG');
                        if(picDom) {
                            obj["picture"] = picDom.currentSrc;
                            obj["imageUrls"].push(picDom.currentSrc)
                        }
                    }
                }
            })
        }
    } else if(platform === '京东') {
        var picGallerys = document.getElementById("spec-list").getElementsByClassName("lh");
        if(picGallerys) {
            obj["imageUrls"] = [];
            var picGalChildren = picGallerys[0].children;
            if(picGalChildren && picGallerys[0].childElementCount > 0) {
                //取第一张图片
                var pictures = picGallerys[0].getElementsByTagName("IMG");
                if(pictures && pictures.length > 0) {
                    Array.from(pictures).forEach(item => {
                        var src = item.src;
                        if(src.indexOf("50x66") > -1) {
                            obj["picture"] = item.src.replace("50x66", "350x467");
                            obj["imageUrls"].push(item.src.replace("50x66", "350x467"))
                        } else if(src.indexOf("/n5/") > -1) {
                            obj["picture"] = item.src.replace("/n5/", "/n1/");
                            obj["imageUrls"].push(item.src.replace("/n5/", "/n1/"));
                        } else {
                            obj["picture"] = item.src;
                            obj["imageUrls"].push(item.src);
                        }
                    })
                }
            }
        }
    } else if(platform == '1688') {
        var picDoms = document.getElementsByClassName("detail-gallery-img");
        if(picDoms) {
            obj["imageUrls"] = [];
            obj["imageUrls"].push(...Array.from(document.getElementsByClassName("detail-gallery-img")).map(item => item.currentSrc));
            obj["picture"] = obj["imageUrls"][0];
        }
    } else if(platform == '抖音') {
        var picDoms = document.getElementsByClassName("head-figure__media-view__video__main-pic");
        if(picDoms && picDoms.length > 0) {
            obj["imageUrls"] = [];
            obj["imageUrls"].push(picDoms[0].src);
            obj["picture"] = obj["imageUrls"][0];
        } else {
            picDoms = document.getElementsByClassName("head-figure__media-view__content");
            if(picDoms && picDoms.length > 0) {
                var picDom = picDoms[0];
                obj["imageUrls"] = [];
                for(var i = 0 ; i < picDoms.length; i ++) {
                    var url = picDoms[i].style.backgroundImage;
                    if(url.indexOf("url(\"") > -1) {
                        obj["imageUrls"].push(url.replace("url(\"", "").replace("\")",""));
                    }
                }
                obj["picture"] = obj["imageUrls"][0];
            }
        }
    } else if(platform == '搜鞋') {
        obj["imageUrls"] = [];
        var picDom = document.getElementById('lnk_thumb');
        var picGallerys = document.querySelector("#photoSmall").childNodes;
        if(picGallerys && picGallerys.length > 0 && picDom) {
            for(var i = 0 ; i < picGallerys.length; i++) {
                var ret = picGallerys[i].dispatchEvent(new MouseEvent('mouseover', {}));
                if(ret) {
                    obj["imageUrls"].push(picDom.src);
                }
            }
            obj["picture"] = obj["imageUrls"][0];
        }
    } else if(platform == '小红书') {
        obj["imageUrls"] = [];
        var picGallerys = document.querySelectorAll(".carousel-image");
        if(picGallerys && picGallerys.length > 0) {
            for(var i = 0 ; i < picGallerys.length; i++) {
                obj["imageUrls"].push(picGallerys[i].src);
            }
            obj["picture"] = obj["imageUrls"][0];
        }
    }
    var array = obj["imageUrls"];
    if(array && array.length > 0) {
        obj["imageUrls"] = array.filter((item, index) => array.indexOf(item) === index);
    }
}

function getBaseInfoFromSx(retItems) {
    var baseInfos = new Array();
    var contents = new Array();
    var details = document.getElementsByClassName('shop-details');
    if(details) {
        var childNodes = details[0].childNodes;
        for(var i  = 0; i < childNodes.length; i++) {
            var content = childNodes[i];
            var emContent = content.getElementsByTagName("em");
            var contentValue = childNodes[i].innerText;
            if(emContent && emContent.length > 0) {
                //contentValue = contentValue.substring(0, idx);
                contentValue = "";
                for(var j = 0; j < content.childNodes.length; j++) {
                    if('#text' ==  content.childNodes[j].nodeName) {
                        contentValue += content.childNodes[j].data;
                    } else {
                        contentValue += content.childNodes[j].innerText + " ";
                    }
                }
            } 
            contents.push(contentValue);
        }
    }
    for(var i  = 0; i < contents.length; i++) {
        var content = contents[i];
        // 抽取关键字段
        for (let [key, value] of keyWords) {
            //关键字信息需要额外抽取
            for(var j = 0; j < value.length; j++) {
                var val;    //输出的值
                var matchWord = matchWords.get(key);
                if(content.indexOf(value[j]) > -1) {
                    var strIdx = content.indexOf("：");
                    var strIdx1 = content.indexOf(":");
                    if(strIdx > -1 && !retItems[key]) {
                        val = content.substring(strIdx + 1);
                    } else if(strIdx1 > -1 && !retItems[key]){
                        val = content.substring(strIdx1 + 1);
                    }
                     // 是否有正则匹配的要求
                    if(matchWord && val && !retItems[key]) {
                        let mathcFound = val.match(matchWord);
                        if(mathcFound && mathcFound.length > 0) {
                            // 去重
                            var uniqueMatches = [...new Set(mathcFound)];
                            val = uniqueMatches[0];
                        }
                    }
                    if(!retItems[key] && val) {
                        retItems[key] = val;
                    } 
                }
            }
        }
        baseInfos.push(content);
    }
    var extraPrice = retItems['extraPrice'];
    if(extraPrice && extraPrice != '' && !isNaN(extraPrice)) {
        retItems["price"] = retItems['extraPrice']
    }
    retItems["base"] = baseInfos;
}

function getBaseInfoFromJD(retItems) {
    var dataMaps = new Map(); 
    var baseInfos = new Array();
    var table = document.querySelector('.p-parameter');
    if(table) {
        var currentTable = table;
        var parameterBrand = currentTable.querySelector('#parameter-brand');    //品牌
        if(parameterBrand) {
            var content = parameterBrand.innerText;
            baseInfos.push(content);
            dataMaps.set("品牌", getValueFromInnerText(content));
        }
        var path1 = document.getElementById("choose-attr-1");
        var path2 = document.getElementById("choose-attr-2");

        //价钱
        var price = document.getElementsByClassName("p-price")[0].children[1].innerText;
        retItems["price"] = price;

        //店铺名称
        var shop = document.getElementsByClassName("contact fr clearfix shieldShopInfo")[0].getElementsByClassName("name")[1].innerText;
        retItems["shop"] = shop;

        if(path1 && path1.innerText.indexOf("颜色") > -1){
            var sp1 = path1.children;
            var items = Array.from(sp1).find(item => item.className === 'dd').children
            if(items && items.length > 0) {
                if(items instanceof HTMLCollection) {
                    retItems["color"] = Array.from(items).map(item => item.dataset.value).join(" ")
                }
            }
        }
        if(path2 && path2.innerText.indexOf("尺码") > -1){
            var sp2 = path2.children;
            var items = Array.from(sp2).find(item => item.className === 'dd').children
            if(items && items.length > 0) {
                if(items instanceof HTMLCollection) {
                    retItems["size"] = Array.from(items).map(item => item.dataset.value).join(" ")
                }
            }
        }
        var dom = document.getElementsByClassName("parameter2 p-parameter-list");
        if(dom) {    
            var details = Array.from(dom[0].children);
            for(var i  = 0; i < details.length; i++) {
                var content = details[i].innerText;
                var vals = getValueFromInnerText(content);
                dataMaps.set(content.substring(0, content.indexOf("：")), vals);
                baseInfos.push(content);
            }
            //填充基本信息
            for (let [key, value] of dataMaps) {
                for (let [kkey, kvalue] of keyWords) {
                    //关键字信息需要额外抽取
                   for(var j = 0; j < kvalue.length; j++) {
                       var val;    //输出的值
                       var matchWord = matchWords.get(kkey);
                       if(key.indexOf(kvalue[j]) > -1) {
                            if(!retItems[key]) {
                                val = value;
                            }
                            // 是否有正则匹配的要求
                            if(matchWord && val && !retItems[key]) {
                                let mathcFound = val.match(matchWord);
                                if(mathcFound && mathcFound.length > 0) {
                                    val = mathcFound.join(","); //mathcFound[0];
                                }
                            }
                            if(!retItems[kkey] && val) {
                                retItems[kkey] = val;
                            } 
                       }
                   }
               }
            }
        }
        retItems["base"] = baseInfos;
    }
}

function getBaseInfoFromVip(retItems) {
    var dataMaps = new Map(); 
    var baseInfos = new Array();
    var table = document.querySelector('.dc-table');
    if(table) {
        var currentTable = table;
        var tableBody = currentTable.querySelector('.J_dc_table');
        if(tableBody) {
            var body = tableBody;
            //根据th <==> tr获取所有标签 <==> 信息
            var rows = body.querySelectorAll('tr');
            for (var i = 0; i < rows.length; i++) {
                var thCells = rows[i].querySelectorAll('th'); // 获取当前行的所有单元格
                var tdCells = rows[i].querySelectorAll('td'); 
                // 遍历当前行的每一个单元格
                for (var j = 0; j < thCells.length; j++) {
                    var th = thCells[j];
                    var td = tdCells[j];
                    dataMaps.set(th.textContent, td.textContent);
                    baseInfos.push(th.textContent + td.textContent);
                }
            }
            //填充基本信息
            for (let [key, value] of dataMaps) {
                //关键字信息
                for (const [kkey, kvalue] of keyWords) {
                    for(var j = 0; j < kvalue.length; j++) {
                        var val;    //输出的值
                        var matchWord = matchWords.get(kkey);
                        if(key.indexOf(kvalue[j]) > -1) {
                            if(!retItems[key]) {
                                val = value;
                            }
                            // 是否有正则匹配的要求
                            if(matchWord && val && !retItems[key]) {
                                let mathcFound = val.match(matchWord);
                                if(mathcFound && mathcFound.length > 0) {
                                    val = mathcFound.join(","); //mathcFound[0];
                                }
                            }
                            if(!retItems[kkey] && val) {
                                retItems[kkey] = val;
                            } 
                        }
                    }
                }
            }
        }
    }
    retItems["base"] = baseInfos;
}

function getBaseInfoFromXhs(retItems) {
    var dataMaps = new Map(); 
    var baseInfos = new Array();
    
    var price = document.getElementsByClassName('price-left')[0].getElementsByTagName("span")[1].innerText;
    retItems["price"] = price;
    retItems["base"] = baseInfos;
}

function getBaseInfoFromDy(retItems) {
    var dataMaps = new Map(); 
    var baseInfos = new Array();
    var keys = document.querySelectorAll('.product-param__params__content__item__content__row__key');
    var values = document.querySelectorAll('.product-param__params__content__item__content__row__value');
    for (var i = 0; i < keys.length; i++) {
        // 遍历当前行的每一个单元格
        var key = keys[i].innerText;
        var value= values[i].innerText;
        dataMaps.set(key, value);
        baseInfos.push(key + ":" + value);
    }
    //填充基本信息
    for (let [key, value] of dataMaps) {
        //关键字信息
        for (const [kkey, kvalue] of keyWords) {
            for(var j = 0; j < kvalue.length; j++) {
                var val;    //输出的值
                var matchWord = matchWords.get(kkey);
                if(key.indexOf(kvalue[j]) > -1) {
                    if(!retItems[key]) {
                        val = value;
                    }
                    // 是否有正则匹配的要求
                    if(matchWord && val && !retItems[key]) {
                        let mathcFound = val.match(matchWord);
                        if(mathcFound && mathcFound.length > 0) {
                            val = mathcFound.join(","); //mathcFound[0];
                        }
                    }
                    if(!retItems[kkey] && val) {
                        retItems[kkey] = val;
                    } 
                }
            }
        }
    }
    retItems["base"] = baseInfos;
    var extraPrice = retItems['extraPrice'];
    if(extraPrice && extraPrice != '' && !isNaN(extraPrice)) {
        retItems["price"] = retItems['extraPrice']
    }
}

function getBaseInfoFrom1688(retItems) {
    //打开详情页面
    var doms = document.getElementsByClassName('layout-right-tab-nav')[0].children;
    var activeTab = Array.from(doms).find(item => item.innerText == '商品属性')
    if(!activeTab) {
        activeTab = doms[0];
    }
    var baseInfos = new Array();
    if(activeTab) {
        activeTab.click();
        var details = Array.from(document.getElementsByClassName("offer-attr-item")).map(item => item.innerText.replace("\n",":"));
        var length = details.length;
        for(var i = 0; i < length; i ++) {
            var content = details[i];
            for (let [key, value] of keyWords) {
                 //关键字信息需要额外抽取
                 for(var j = 0; j < value.length; j++) {
                    var val;    //输出的值
                    var matchWord = matchWords.get(key);
                    if(content.indexOf(value[j]) > -1) {
                        var strIdx1 = content.indexOf(":");
                        if(strIdx1 > -1 && !retItems[key]){
                            val = content.substring(strIdx1 + 1);
                        }
                        if(matchWord && val && !retItems[key]) {
                            let mathcFound = val.match(matchWord);
                            if(mathcFound && mathcFound.length > 0) {
                                // 去重
                                var uniqueMatches = [...new Set(mathcFound)];
                                val = uniqueMatches[0];
                            }
                        }
                        if(!retItems[key] && val) {
                            retItems[key] = val;
                        } 
                    }
                 }
            }
            baseInfos.push(content);
        }
    }
    retItems["base"] = baseInfos;
    //历史销量
    var rightDom = document.getElementsByClassName("layout-right")[0].childNodes;
    var saleDom = Array.from(rightDom).find(item => item.className === '');
    if(saleDom) {
       var dom = saleDom.childNodes[2]
        var s0 = dom.childNodes[0].innerText
        let mathcFound = s0.match(/(\d{4})/g);
        if(mathcFound && mathcFound.length > 0) {
            retItems[saleDesc] = mathcFound[0]
        }
    }
    var shop = document.getElementById("hd_0_container_0").getElementsByTagName("span")[0].innerText;
    retItems["shop"] = shop;
    //销量

    var saleColumn = document.getElementsByClassName("title-sale-column")
    if(saleColumn) {
        var number = saleColumn[0].getElementsByClassName("title-info-number")[0].innerText;
        retItems["saleDesc"] = number;
    }
}

function getBaseInfoFromTb(retItems) {
    var details = document.getElementsByClassName("Attrs--attr--33ShB6X");
    //获取基础参数
    var contents = new Array();
    var baseInfos = new Array();
    if(details && details.length > 0) {    
        for(var i  = 0; i < details.length; i++) {
            var content = details[i].innerText;
            contents.push(content);
            
        }
    } else {
        details = document.getElementsByClassName('InfoItem--infoItem--zCvv3MH');
        if(!details || details.length == 0) {
            details = document.getElementsByClassName('infoItem--Z4hNxv8b');
        }
        if(details && details.length > 0) {    
            for(var i  = 0; i < details.length; i++) {
                var content = details[i].innerText;
                contents.push(content.replaceAll("\n",":"));
            }
        }
    }
    for(var i  = 0; i < contents.length; i++) {
        var content = contents[i];
        // 抽取关键字段
        for (let [key, value] of keyWords) {
            //关键字信息需要额外抽取
            for(var j = 0; j < value.length; j++) {
                var val;    //输出的值
                var matchWord = matchWords.get(key);
                if(content.indexOf(value[j]) > -1) {
                    var strIdx = content.indexOf("：");
                    var strIdx1 = content.indexOf(":");
                    if(strIdx > -1 && !retItems[key]) {
                        val = content.substring(strIdx + 1);
                    } else if(strIdx1 > -1 && !retItems[key]){
                        val = content.substring(strIdx1 + 1);
                    }
                     // 是否有正则匹配的要求
                    if(matchWord && val && !retItems[key]) {
                        let mathcFound = val.match(matchWord);
                        if(mathcFound && mathcFound.length > 0) {
                            // 去重
                            var uniqueMatches = [...new Set(mathcFound)];
                            val = uniqueMatches[0];
                        }
                    }
                    if(!retItems[key] && val) {
                        retItems[key] = val;
                    } 
                }
            }
        }
        baseInfos.push(content);
    }
    var extraPrice = retItems['extraPrice'];
    if(extraPrice && extraPrice != '' && !isNaN(extraPrice)) {
        retItems["price"] = retItems['extraPrice']
    }
    retItems["base"] = baseInfos;
}

function getValueFromInnerText(innerText) {
    var val;
    var strIdx = innerText.indexOf("：");
    var strIdx1 = innerText.indexOf(":");
    if(strIdx > -1) {
        val = innerText.substring(strIdx + 1);
    } else if(strIdx1 > -1){
        val = innerText.substring(strIdx1 + 1);
    }
    return val;
}